// utils/http.ts
import Taro from '@tarojs/taro'
import {globalState} from "@/store/globalStore";
import { buildUrlParams } from './tooler';
import { apiConfig } from "@/utils/config";

// 定义基础配置类型
interface RequestConfig {
  baseURL?: string
  timeout?: number
  headers?: Record<string, string>
}

// 定义请求选项类型
interface RequestOptions {
  url: string
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'
  data?: any
  headers?: Record<string, string>
  loadingText?: string
  showLoading?: boolean
}

// 定义响应类型
interface ResponseData<T = any> {
  code: number
  message: string
  data: T
}

class HttpRequest {
  private config: RequestConfig

  constructor(config: RequestConfig = {}) {
    this.config = {
      baseURL: config.baseURL || '', // 基础路径
      timeout: config.timeout || 15000, // 默认15秒超时
      headers: {
        'Content-Type': 'application/json',
        ...(config.headers || {})
      }
    }
  }

  /**
   * 核心请求方法
   */
  private async request<T>(options: RequestOptions): Promise<ResponseData<T>> {
    const { showLoading = true, loadingText = '加载中...' } = options

    // 显示加载提示
    if (showLoading) {
      Taro.showLoading({
        title: loadingText,
        mask: true
      })
    }

    try {
      // 合并请求配置
      const headerData: any = {
        'Token': globalState?.token || '1',
        ...this.config.headers,
        ...(options.headers || {})
      }
      
      if(options.url.includes('getToken')){
        delete headerData['token'];
        headerData['Token'] = '1'
      }
      console.log('headerData', headerData)
      const mergedOptions: Taro.request.Option = {
        url: this.config.baseURL + options.url,
        method: options.method || 'GET',
        data: options.data || {},
        header: headerData,
        timeout: this.config.timeout
      }

      // 发起请求
      const response = await Taro.request(mergedOptions)

      // 关闭加载提示
      if (showLoading) {
        Taro.hideLoading()
      }

      // 处理响应数据
      if (response.statusCode >= 200 && response.statusCode < 300) {
        return response.data as ResponseData<T>
      } else {
        throw this.handleError(response)
      }
    } catch (error) {
      // 关闭加载提示
      if (showLoading) {
        Taro.hideLoading()
      }
      throw this.handleError(error)
    }
  }

  /**
   * 错误处理方法
   */
  private handleError(error: any) {
    console.error('请求错误:', error)
    
    // 统一错误提示
    let errMsg = '请求失败，请稍后重试'
    if (error.errMsg) {
      errMsg = error.errMsg
    } else if (error.message) {
      errMsg = error.message
    }

    Taro.showToast({
      title: errMsg,
      icon: 'none',
      duration: 2000
    })

    return new Error(errMsg)
  }

  /**
   * GET 请求
   */
  public async get<T>(url: string, params?: any, options?: Omit<RequestOptions, 'url' | 'method' | 'data'>) {
    // 将参数拼接到URL上
    let queryString = ''
    if (params) {
      queryString = Object.keys(params)
        .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
        .join('&')
      url += (url.includes('?') ? '&' : '?') + queryString
    }

    return this.request<T>({
      url,
      method: 'GET',
      ...options
    })
  }

  /**
   * POST 请求
   */
  public async post<T>(url: string, data?: any, options?: Omit<RequestOptions, 'url' | 'method' | 'data'>) {
    return this.request<T>({
      url,
      method: 'POST',
      data,
      ...options
    })
  }

  public async postQuery<T>(url: string, data?: any, options?: Omit<RequestOptions, 'url' | 'method' | 'data'>) {
    url = buildUrlParams(url, data);
    return this.request<T>({
      url,
      method: 'POST',
      data,
      ...options
    })
  }



  /**
   * PUT 请求
   */
  public async put<T>(url: string, data?: any, options?: Omit<RequestOptions, 'url' | 'method' | 'data'>) {
    return this.request<T>({
      url,
      method: 'PUT',
      data,
      ...options
    })
  }

  /**
   * DELETE 请求
   */
  public async delete<T>(url: string, data?: any, options?: Omit<RequestOptions, 'url' | 'method' | 'data'>) {
    return this.request<T>({
      url,
      method: 'DELETE',
      data,
      ...options
    })
  }
}

// 创建默认实例
const http = new HttpRequest({
  baseURL: apiConfig.baseURL, // 替换为你的API基础地址
  // baseURL: 'http://192.168.1.11:8081',
  timeout: apiConfig.timeout
})

export default http